package com.alibaba.cirtus.ots.application.adapter.ability.facade.serviceV2.sap;

import com.alibaba.cirtus.ots.application.adapter.ability.model.Result;
import com.alibaba.cirtus.ots.application.adapter.ability.utils.HttpTokenUtil;
import com.alibaba.cirtus.ots.application.adapter.ability.utils.HttpUtils;
import com.alibaba.citrus.ots.common.annotation.ProcessInvoker;
import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.epoch.app.otsapplicationadaptersdk.contants.OtsApplicationAdapterSdkConstants;
import com.epoch.app.otsapplicationadaptersdk.mnsapif035v2.dto.ShippingOrderCallbackRequest;
import com.epoch.app.otsapplicationadaptersdk.mnsapif035v2.service.MnSapIf035V2Service;
import com.epoch.app.otsapplicationadaptersdk.sap.MnSapCommResponse;
import com.epoch.app.otsapplicationadaptersdk.sap.MnSapCommSDO;
import com.google.common.base.Throwables;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

/**
 * @author baizhuo
 * @version 1.0
 * @date 2024/1/5 10:47
 */
@Component
@Primary
public class MnSapIf035V2ServiceImpl implements MnSapIf035V2Service {

    private final Log log = Log.getLogger(MnSapIf035V2ServiceImpl.class);

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private HttpUtils httpUtils;

    /**
     * TODO 创建装运单回调
     * 待处理项：
     *  1. 装运单回调MessageHeader 中没有messageId 和interface, 需要确认回调返回值的问题？
     *  2. 修改装运单回调的处理逻辑待确认
     *  3. 删除装运单回调的处理逻辑待确认
     * @param mnSapIf035Request
     * @return
     */
    @Override
    @ProcessInvoker(remark = "MnSapIf035V2Service", errorCode = "OTS-02-007-00-16-999", printLog = true)
    public MnSapCommResponse shippingOrderCallback(ShippingOrderCallbackRequest mnSapIf035Request) {
        log.info("MnSapIf035V2ServiceImpl shippingOrderCallback param:{}", JSON.toJSONString(mnSapIf035Request));
        MnSapCommResponse mnSapCommResponse = new MnSapCommResponse();
        MnSapCommSDO mnSapCommSDO = new MnSapCommSDO();
        CallbackSDD callbackSDD = caseToCallbackSDD(mnSapIf035Request.getMessage());
        if (callbackSDD == null){
            log.info("MnSapIf035V2ServiceImpl shippingOrderCallback callbackSDD is null");
            return mnSapCommResponse;
        }
        shippingOrderCallbackHandler(callbackSDD);
        return mnSapCommResponse;
    }


    /**
     * 处理 装运单SAP 回调
     * @param sdd
     */
    private void shippingOrderCallbackHandler(CallbackSDD sdd){
        log.info("MnSapIf035V2ServiceImpl shippingOrderCallbackHandler:sdd:{}", JSON.toJSONString(sdd));
        switch (sdd.getSubmitType()){
            case 1:
                createShippingOrderHandler(sdd);
                break;
            case 2:
                // todo wxy 调用bcLink
                log.info("MnSapIf035V2ServiceImpl shippingOrderCallbackHandler:修改回调，待处理");
                break;
            case 3:
                log.info("MnSapIf035V2ServiceImpl shippingOrderCallbackHandler:删除回调，待处理");
                break;
            default:
                break;
        }
    }

    /**
     * 处理创建装运单回调
     * @param sdd
     */
    private void createShippingOrderHandler(CallbackSDD sdd){
        log.info("MnSapIf035V2ServiceImpl createShippingOrderHandler param:{}", JSON.toJSONString(sdd));
        //if (sdd.getCode() != 0){
        //    log.info("MnSapIf035V2ServiceImpl createShippingOrderHandler:error 创建装运单失败");
        //    return;
        //}
        Map<String, String> header = HttpTokenUtil.generateHttpHeader();
        String urlPrefix = OtsApplicationAdapterSdkConstants.urlPrefix();
        String url = urlPrefix + "api/mn_bc_link/createShippingOrderCallback";
        log.info("test http header:{}, url:{}", header, url);
        try {
            JSONObject param = new JSONObject();
            param.put("shippingOrderNo", sdd.getUniqueCode());
            param.put("outOrderNo", sdd.getTransportNo());
            param.put("code", sdd.getCode());
            param.put("submitType", sdd.getSubmitType());
            param.put("message", sdd.getMessage());
            log.info("MnSapIf035V2ServiceImpl createShippingOrderHandler call bc link interface,url:{}, header:{}, param:{}", url, header, JSON.toJSONString(param));
            ResponseEntity<Result> post = httpUtils.post(url, header, param, Result.class);
            Result result = post.getBody();
            log.info("MnOtwIf010Service shippingOrderCreateSync mnOtwCommonResponse result:{}", JSON.toJSONString(result));
        } catch (Exception e) {
            log.error("call bc-link inOutBoundFinishResultSync error", e);
        }
    }

    /**
     * 将入参转换为装运单回调通用对象
     * @param json
     * @return
     */
    private CallbackSDD caseToCallbackSDD(String json){
        log.info("MnSapIf035V2ServiceImpl caseToCallbackSDD, json:{}", json);
        CallbackSDD sdd = null;
        try {
            sdd = JSON.parseObject(json, CallbackSDD.class);
        }catch (Exception e){
            log.info("MnSapIf035V2ServiceImpl caseToCallbackSDD, error:{}", Throwables.getStackTraceAsString(e));
        }
        log.info("MnSapIf035V2ServiceImpl caseToCallbackSDD, sdd:{}", JSON.toJSONString(sdd));
        return sdd;
    }


    @Data
    static class CallbackSDD{

        // 状态码，0-成功，1-失败
        private Integer code;

        // 返回描述
        private String message;

        // 操作码：1-创建，2-修改，3-删除
        private Integer submitType;

        // 中台装运单号
        private String uniqueCode;

        // SAP 装运单号
        private String transportNo;
    }
}
